/*****************************************************************************************************/
var kk = kk || {};

kk.getRootPath = function() {
    var curWwwPath = window.document.location.href;				// 获取当前网址，如： http://localhost:8080/ems/Pages/Basic/Person.jsp
    var pathName = window.document.location.pathname;			// 获取主机地址之后的目录，如： /ems/Pages/Basic/Person.jsp
    var pos = curWwwPath.indexOf(pathName);
    var localhostPath = curWwwPath.substring(0, pos);			// 获取主机地址，如： http://localhost:8080
    var projectName = pathName.substring(0, pathName.substr(1).indexOf('/') + 1);		// 获取带"/"的项目名，如：/ems
    return (localhostPath + projectName);
}

kk.getProjectName = function() {
    var pathName = window.document.location.pathname;			// 获取主机地址之后的目录，如： /ems/Pages/Basic/Person.jsp
    var projectName = pathName.substring(0, pathName.substr(1).indexOf('/') + 1);		// 获取带"/"的项目名，如：/ems
    return projectName.substring(1, projectName.length);
}

var rootPath = kk.getRootPath();								// rootPath ==> kk.rootPath +++

/* 加载成功后回调函数（只处理data.code错误） */
kk.onLoadSuccess = function(data) {
	if (!data || !data.hasOwnProperty("code")) {
		console.log('err: !data || !data.hasOwnProperty("code")...');
		return false;
	}

	if (data.code == 0) {
		return false;
	}
	
	switch (data.code) {
	case 401:
		title = '未授权';
		break;
	case 404:
		title = '未找到';
		break;
	case 408:
	   	xpopup.alert({
		    type: 'error',
	       	title: '登录超时',
	        msg: data.msg,
	        buttons: [{
                text: 'OK',
                'class': '',
                handler: function ($this) {
            		$this.destroy();
        			location.replace(kk.getRootPath() + '/admin/login.jsp');
                }
            }]
	    });
		break;
	case 417:
		title = '未满足期望值';
		break;
	case 499:
		title = '错误';
		break;
	default:
		title = '错误';
		break;
	}
	
	if (data.code != 408) {
		xpopup.alert({
		    type: 'error',
	       	title: title,
	        msg: data.msg,
	        buttons: [{
                text: 'OK',
                'class': '',
                handler: function ($this) {
            		$this.destroy();
                }
            }]
	    });
	}
}

/* 通用错误提示（处理ajax error错误） */
kk.extError = function(xhr, xloading) {
	xloading.destroy();
	
   	xpopup.alert({
	    type: 'error',
       	title: 'ERROR',
//        msg: JSON.stringify(data),
        msg: xhr.status + ', ' + xhr.statusText,
        buttons: [{
            text: 'OK',
            'class': '',
            handler: function ($this) {
        		$this.destroy();
            }
        }]
    });
}

/* 通用错误提示  */
kk.onLoadError = function(responseText, textStatus, XMLHttpRequest) {
	if (textStatus == 'error') {
	    var msg = 'Sorry but there was an error: ' + XMLHttpRequest.status + ' ' + XMLHttpRequest.statusText + ' ' + XMLHttpRequest.responseText;
    	xpopup.alert({
		    type: 'error',
	       	title: '加载出错',
	        msg: msg,
	        buttons: [{
                text: 'OK',
                'class': '',
                handler: function ($this) {
            		$this.destroy();
        		//	location.replace(kk.getRootPath() + '/admin/login.jsp');
                }
            }]
	    });
	}
}

//$.extend($.fn.bootstrapTable.defaults, { onLoadSuccess: kk.onLoadSuccess }, { onLoadError: kk.onLoadError });
//$.extend(xtreetable.defaults, { onLoadSuccess: kk.onLoadSuccess }, { onLoadError: kk.onLoadError });
//$.extend(xmenutree.defaults, { onLoadSuccess: kk.onLoadSuccess }, { onLoadError: kk.onLoadError });
if ($.fn.bootstrapTable !== undefined) {
	$.extend($.fn.bootstrapTable.defaults, { onLoadSuccess: kk.onLoadSuccess }, { onLoadError: kk.onLoadError });
}
if (typeof(xtreetable) !== 'undefined') {
	$.extend(xtreetable.defaults, { onLoadSuccess: kk.onLoadSuccess }, { onLoadError: kk.onLoadError });
}
if (typeof(xmenutree) !== 'undefined') {
	$.extend(xmenutree.defaults, { onLoadSuccess: kk.onLoadSuccess }, { onLoadError: kk.onLoadError });
}

/**											
 * 将form表单元素的值序列化成JSON对象，两种风格
 */
kk.serializeObject = function(form) {									// MUST
	var o = {};
	$.each(form.serializeArray(), function(index) {
		if (o[this['name']]) {
			o[this['name']] = o[this['name']] + ',' + this['value'];
		} else {
			o[this['name']] = this['value'];
		}
	});
	return o;
};

$.fn.serializeObject = function() {
   var o = {};
   var a = this.serializeArray();
   $.each(a, function() {
       if (o[this.name]) {
           if (!o[this.name].push) {
               o[this.name] = [o[this.name]];
           }
           o[this.name].push(this.value || '');
       } else {
           o[this.name] = this.value || '';
       }
   });
   return o;
};

/**
 * 序列化值为''替换为‘无’，以使''的input也能参与组建对象
 */
$.fn.serializeObjectExt = function() {
   var o = {};
   var a = this.serializeArray();
   $.each(a, function() {
       if (o[this.name]) {
           if (!o[this.name].push) {
               o[this.name] = [o[this.name]];
           }
    	   o[this.name].push(this.value || '无');
       } else {
           o[this.name] = this.value || '无';
       }
   });
   return o;
};

/**
 * js毫秒time转化为时间并格式化显示代码，time不存在时，获取当前的日期时间
 */
kk.timeFormat = function(format, time) {
	var t = time ? new Date(time) : new Date();
	var tf = function(i) {
		return (i < 10 ? '0' : '') + i;
	};
	return format.replace(/yyyy|MM|dd|HH|mm|ss|SSS/g, function(a) {
		switch (a) {
		case 'yyyy':
			return tf(t.getFullYear());
			break;
		case 'MM':
			return tf(t.getMonth() + 1);
			break;
		case 'mm':
			return tf(t.getMinutes());
			break;
		case 'dd':
			return tf(t.getDate());
			break;
		case 'HH':
			return tf(t.getHours());
			break;
		case 'ss':
			return tf(t.getSeconds());
			break;
		case 'SSS':
			return tf(checkTime(t.getMilliseconds()));
			break;
		}
	}); 
};

/**
 * Data类型格式化显示
 * 返回格式化后的字符串
 * //使用方法
	var now = new Date();
	var nowStr = now.format("yyyy-MM-dd hh:mm:ss");
	//使用方法2:
	var testDate = new Date();
	var testStr = testDate.format("YYYY年MM月dd日hh小时mm分ss秒");
	alert(testStr);
	//示例：
	alert(new Date().Format("yyyy年MM月dd日"));
	alert(new Date().Format("MM/dd/yyyy"));
	alert(new Date().Format("yyyyMMdd"));
	alert(new Date().Format("yyyy-MM-dd hh:mm:ss"));
 */
Date.prototype.format = function(format) {
	var o = {
		"M+" : this.getMonth() + 1, 						// month
		"d+" : this.getDate(), 								// day
		"h+" : this.getHours(), 							// hour
		"m+" : this.getMinutes(), 							// minute
		"s+" : this.getSeconds(), 							// second
		"q+" : Math.floor((this.getMonth() + 3) / 3), 		// quarter
		"S" : checkTime(this.getMilliseconds())				// ext millisecond
	}

	if (/(y+)/.test(format)) {
		format = format.replace(RegExp.$1, (this.getFullYear() + "")
				.substr(4 - RegExp.$1.length));
	}

	for ( var k in o) {
		if (new RegExp("(" + k + ")").test(format)) {
			format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k]
					: ("00" + o[k]).substr(("" + o[k]).length));
		}
	}
	
	return format;
}

function checkTime(i){
    if (i<100 && i>9){
        i = "0" + i;
    }
    if (i<10){
        i = "00" + i;
    }
    return i;
}

/******************************************************/
/* 异步提交表单 -- POST or PUT */
kk.doStrAjax = function(url, type, dataStr) {
    var xloading = xpopup.loading();
    
	var result;
	$.ajax({
        type: type,
        url: url,
        contentType: 'application/json',
		data: dataStr,										// dataStr参数是字符串 !!!
        dataType: 'json',
		async: false,
        success: function (data) {
        	xloading.destroy();
        	
			result = data;
        	var type;
			if (data.code == 0) {
		   		xpopup.notify({
		           	style: 'mini',
		           	type: 'success',
//		           	title: '操作成功',
					msg: data.msg,
					delay: 1000,
					position: 'center',
				});
			} else {
				kk.onLoadSuccess(data);
			}
		//	alert.destroy();								// 关闭正在处理提示。。。
        },
		error: function (data) {
			kk.extError(data, xloading);
		}
    });
	return result;
}

/* 获得对象 -- GET */
kk.getObj = function(url) {
	var xloading = xpopup.loading();
    
	var obj = null;
	$.ajax({
		type: 'get',
		url: url, 
		data: null,
		dataType: 'json',
		async : false,
		success: function(data) {
        	xloading.destroy();
        	
			if (typeof data.code === 'undefined') {				// 返回普通的、未经data封装的对象
				obj = data;
			} else if (data.code == 0) {
				obj = data.obj;
			} else {
				kk.onLoadSuccess(data);
			}
  		},
		error: function (data) {
			kk.extError(data, xloading);
		}
	});
	return obj;
}

/* 删除对象 -- DELETE */
kk.deleteObj = function(url, refreshObj, msg) {
	xpopup.confirm({
    	title: '确认',
        msg: '您确定要删除？' + (msg ? '<br/><span style="color: red;">' + msg + '</span>' : ''),
        buttons: [{
            text: '是',
            'class': 'btn btn-danger btn-flat',
            handler: function ($this) {
                var xloading = xpopup.loading();
                
    			$.ajax({
    				type: 'DELETE',
    				url : url,
    				dataType: 'json',
    				async : false,
    				success: function(data) {
    		        	xloading.destroy();
    		        	
    					if (data.code == 0) {
    	    		   		xpopup.notify({
    	    		           	style: 'mini',
    	    		           	type: 'success',
//    	    		           	title: '操作成功',
    	    					msg: data.msg,
    	    					delay: 1000,
    	    					position: 'center',
    	    				});
    	                	
    	                	try {
        	                	$(refreshObj).bootstrapTable('refresh');								// refresh bootstrap table
        	                	refreshObj.refresh();													// refresh tree table
    	                	} catch(err) {
    	                		//
    	                	}
    					} else {
    						kk.onLoadSuccess(data);
    					}
    				},
    				error: function (data) {
    					kk.extError(data, xloading);
    				}
    			});
    			
        		$this.destroy();
            }
        }, {
            text: '否',
            'class': 'btn btn-default btn-flat',
            handler: function ($this) {
        		$this.destroy();
            }
        }]
    });
}

/* jquery 自动填充form */
$.fn.setForm = function(jsonValue) {
	var self = this;
	
	$.each(jsonValue, function(name, ival) {
		var $oinput = self.find(':input[name="' + name + '"]');
		if ($oinput.attr('type') == 'radio' || $oinput.attr('type') == 'checkbox') {
			$oinput.each(function() {
				if (Object.prototype.toString.apply(ival) == '[object Array]') {		// 是复选框，并且是数组
					for (var i = 0; i < ival.length; i++) {
						if ($(this).val() == ival[i])
							$(this).attr('checked', 'checked');
					}
				} else {
					if ($(this).val() == ival)
						$(this).attr('checked', 'checked');
				}
			});
		} else if ($oinput.attr('type') == 'textarea') {								// 多行文本框    		
			self.find('[name="' + name + '"]').html(ival);
		} else {
			self.find('[name="' + name + '"]').val(ival);
		}
	});
	return self;
};

/* jquery 清空form */
$.fn.resetForm = function() {
	var self = this;
	
	self.find(':input').not(':button, :submit, :reset, :hidden')
			.val('')
			.removeAttr('checked').
			removeAttr('selected');
	return self;
};

/* jQuery从URL中提取参数（能解决URL中文乱码问题） */
kk.GetQueryString = function(name) {
	var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
    var result = window.location.search.substr(1).match(reg);
	return result ? decodeURIComponent(result[2]) : null;
};

/* Js随机产生num位数字的代码 */
kk.mathRand = function(num) {
	if (num <= 0) {
		return ;
	}
	
	var numStr = "";
	for (var i = 0; i < num; i++) {
		numStr += Math.floor(Math.random() * 10);
	}

	return numStr;
};

/* 通过正则表达式判断返回值是否为json格式 */
kk.strIsJson = function(str) {
	return str.match("^\{(.+:.+,*){1,}\}$");
}

/* 显示js对象所有属性和方法的函数 */
kk.showObjProperty = function(Obj) {
	var PropertyList = '';
	var PropertyCount = 0;
	for (i in Obj) {
		if (Obj.i != null)
			PropertyList = PropertyList + i + '属性：' + Obj.i + '\r\n';
		else
			PropertyList = PropertyList + i + '方法\r\n';
	}
	console.log(PropertyList);
}

/* 将带有特殊字符的字符串转义为HTML实体编码 */
kk.escapeHtml = function(str) {
    var entityMap = {
        "&": "&amp;",
        "<": "&lt;",
        ">": "&gt;",
        '"': '&quot;',
        "'": '&#39;',
        "/": '&#x2F;'
    };
    return String(str).replace(/[&<>"'\/]/g, function (s) {
        return entityMap[s];
    });
}

/* 获取JSON对象长度 */
kk.getJsonLength = function(jsonData) {
	var jsonLength = 0;
	for (var item in jsonData) {
		jsonLength++;
	}
	return jsonLength;
}